package com.gitee.feizns.itrip.personal.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gitee.feizns.itrip.personal.beans.pojo.UserLinkUser;
import com.gitee.feizns.itrip.personal.biz.entity.ao.ForAcceptQueryLinkUser;
import com.gitee.feizns.itrip.personal.biz.service.UserInfoService;
import com.gitee.feizns.itrip.personal.biz.service.exception.UserLinkUserException;
import com.gitee.feizns.itrip.personal.mapper.UserLinkUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.gitee.feizns.itrip.personal.biz.service.exception.UserLinkUserException.LINK_USER_ID_IS_NOT_NULL;

/**
 * @author feizns
 * @since 2019/1/11 0011
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserLinkUserMapper userLinkUserMapper;

    @Override
    public List<UserLinkUser> queryUserLinkUser(ForAcceptQueryLinkUser linkUser, Long userId) {
        Wrapper<UserLinkUser> condition = new EntityWrapper<UserLinkUser>().and(" userId = {0} ", userId);
        if ( linkUser.getLinkUserName() != null )
            condition.and(" linkUserName like CONCAT({0}, '%') ", linkUser.getLinkUserName());
        return userLinkUserMapper.selectList(condition);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void addUserLinkUser(UserLinkUser user, Long curtUserId) {

        System.out.println(this.getClass().getName());
        //补充数据
        userSupplement(user, curtUserId);

        userLinkUserMapper.insert(user);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void modifyUserLinkUser(UserLinkUser user, Long curtUserId) {

        //补充数据
        userSupplement(user, curtUserId);

        userLinkUserMapper.updateById(user);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int delUserLinkUser(Integer[] intIds) {
        if ( intIds == null || intIds.length == 0 )
             throw new UserLinkUserException(LINK_USER_ID_IS_NOT_NULL, "联系人id不能为空");
        return userLinkUserMapper.deleteBatchIds(Arrays.asList(intIds));
    }

    private void userSupplement(UserLinkUser userLinkUser, Long curtUserId) {
        userLinkUser.setUserId(curtUserId.intValue())
            .setCreatedBy(curtUserId)
            .setCreationDate(new Date());
    }

}
